<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
    :maskClosable="false"
  >
    <BasicForm
      @register="registerForm"
      class="bg-white"
      style="padding: 0.7rem; border-radius: 0.8rem"
    />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { computed } from 'vue';
  import { BasicForm, useForm } from '@/components/Form';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { usePermissionStore } from '@/store/modules/permission';

  import { buttonFormSchema } from './role.data';
  import { CreateRoleButtonParams, CheckBoxOption } from '@/api/system/model/systemModel';
  import { createRoleButton, getRoleButtonList } from '@/api/system/role';
  import { getPermCode } from '@/api/sys/user';

  import { useI18n } from '@/hooks/web/useI18n';
  import { getAll } from '@/api/system/button';

  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const usePermStore = usePermissionStore();

  const emit = defineEmits(['success', 'register']);

  let roleId: Number;

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: buttonFormSchema,
    showActionButtonGroup: false,
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    roleId = data.record?.id;

    setFieldsValue({
      ...data.record,
    });

    // 所有的按钮
    const options: CheckBoxOption[] = [];
    const buttonList = await getAll();
    for (const item of buttonList) {
      options.push({
        label: item['name'],
        value: item['id'],
      });
    }
    // 已勾选授权的按钮
    const roleButtons = await getRoleButtonList(roleId);
    // 动态构建
    updateSchema({
      field: 'buttonList',
      defaultValue: roleButtons,
      componentProps: {
        options: options,
      },
    });
  });

  const getTitle = computed(() => '按钮授权');

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      // TODO custom api
      // 接口参数组装
      let params: CreateRoleButtonParams = {
        role_id: roleId,
        button_ids: values['buttonList'].join(','),
      };
      // 接口请求
      const { code, message } = await createRoleButton(params);

      const { t } = useI18n();
      if (code === 0) {
        // 更新授权的代码
        usePermStore.changePermissionCode();
        createMessage.success(t('sys.api.operationSuccess'), 2, function () {
          closeDrawer();
          emit('success');
        });
      } else {
        createMessage.error(message);
      }
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
